import Vue from 'vue';
import App from './App.vue';
import router from './routes';
import store from './store';
import { Loading } from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import BaiduMap from 'vue-baidu-map';
import Mint from 'mint-ui';
import 'mint-ui/lib/style.css';
import Cookies from 'js-cookie';

Vue.use(Mint);
Vue.use(Loading);

router.beforeEach((to, from, next) => {
  console.log(to);
  let { sourceType } = to.query;
  if (sourceType) {
    sessionStorage.sourceType = sourceType;
  }
  let token = Cookies.get('token');
  if (token) {
    store.dispatch('login', token);
  }
  if (to.matched.length === 0) {
    from.name ? next({ name: from.name }) : next('/home');
  } else {
    if (to.meta.requireAuth) {
      // 判断该路由是否需要登录权限
      if (store.state.token) {
        // 通过vuex state获取当前的token是否存在
        next();
      } else {
        console.log(to.fullPath);
        next({
          path: '/login',
          query: { redirect: to.fullPath } // 将跳转的路由path作为参数，登录成功后跳转到该路由
        });
      }
    } else {
      next();
    }
    /* 如果本地 存在 token 则 不允许直接跳转到 登录页面*/
    if (to.fullPath == '/login') {
      if (store.state.token) {
        next({ path: from.fullPath });
      } else {
        next();
      }
    }
  }
});

Vue.use(BaiduMap, {
  // ak 是在百度地图开发者平台申请的密钥 详见 http://lbsyun.baidu.com/apiconsole/key */
  ak: '3YOCg7ZoHfhOLxtsTDpMVuPs'
});

Vue.config.productionTip = false;

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app');
